/*
 * SunSpotHostApplication.java
 *
 * Created on 4 avr. 2011 16:12:42;
 */

package org.sunspotworld;

import com.sun.spot.peripheral.radio.RadioFactory;
import com.sun.spot.io.j2me.radiogram.*;
import com.sun.spot.util.IEEEAddress;

import java.io.*;
import javax.microedition.io.*;


/**
 * Sample Sun SPOT host application
 */
public class SunSpotHostApplication {

    /**
     * Print out our radio address.
     */
    public void run() {
        long ourAddr = RadioFactory.getRadioPolicyManager().getIEEEAddress();
        System.out.println("Our radio address = " + IEEEAddress.toDottedHex(ourAddr));

        String tmp = null;
        RadiogramConnection dgConnection = null;
        Datagram dg = null;

        try {
            dgConnection = (RadiogramConnection) Connector.open("radiogram://:40");
            // Then, we ask for a datagram with the maximum size allowed
            dg = dgConnection.newDatagram(dgConnection.getMaximumLength());
        } catch (IOException e) {
            System.out.println("Could not open radiogram receiver connection");
            e.printStackTrace();
            return;
        }

        while(true)
        {
            try
            {
                dg.reset();
                dgConnection.receive(dg);
                tmp = dg.readUTF();
                System.out.println("Received: " + tmp + " from " + dg.getAddress());
            }
            catch (IOException e)
            {
                System.out.println("Nothing received");
            }
        }
    }

    /**
     * Start up the host application.
     *
     * @param args any command line arguments
     */
    public static void main(String[] args) {
        SunSpotHostApplication app = new SunSpotHostApplication();
        app.run();
    }
}
